/*
 * @Description: 按键c文件
 * @Author: TzzzT
 * @Date: 2022-04-05 19:05:41
 * @LastEditTime: 2023-04-18 06:25:05
 * @LastEditors: TzzzT
 */
#include "iot_button.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"

#include "RCS_slave.h"
#include "RCS_btn.h"
#include "RCS_ble_slave.h"

static const char *TAG = "RCS_BTN";
extern rcs_slave_system_t rcsSystem;
extern TaskHandle_t bleserverTaskHandle;
extern QueueHandle_t xUploadDataQueue;
button_handle_t gpio_btn;

static void button_single_click_cb(void *arg, void *data)
{
    ESP_LOGI(TAG, "BUTTON_SINGLE_CLICK");
    power_off();
}

static void button_long_click_cb(void *arg, void *data)
{
    ESP_LOGI(TAG, "BUTTON_LONG_CLICK");
    if (rcsSystem.device.is_connect_master == CONNECTED_BLE)
    {
        uint8_t pack_len = 0;
        uint8_t *package = make_disconnect_package(&pack_len);
        ESP_LOGI(TAG, "put make_disconnect_package in queue");
        if (xQueueSend(xUploadDataQueue, package, pdMS_TO_TICKS(40)) != pdPASS)
        {
            ESP_LOGI(TAG, "queue full, try to connect ble server then send queue data to server.");
        }
        free(package);
    }
    rcsSystem.device.wait_new_master = true;
    if (eTaskGetState(bleserverTaskHandle) == eSuspended)
    {
        ESP_LOGE(TAG, "vTaskResume( bleserverTaskHandle )");
        vTaskResume(bleserverTaskHandle);
    }
}

/**
 * @description: 按键初始化
 * @param  {void}
 * @return {void}
 * @Author: TzzzT
 * @Date: 2022-04-19 23:51:14
 * @LastEditTime: Do not edit
 * @LastEditors: Shadow
 */
void btn_init(void)
{
    // create gpio button
    button_config_t gpio_btn_cfg = {
        .type = BUTTON_TYPE_GPIO,
        .gpio_button_config = {
            .gpio_num = BTN_GPIO_NUM,
            .active_level = 0,
        },
    };
    gpio_btn = iot_button_create(&gpio_btn_cfg);
    if (NULL == gpio_btn)
    {
        ESP_LOGE(TAG, "Button create failed");
    }
}

void register_btn(void)
{
    if (NULL == gpio_btn)
    {
        ESP_LOGE(TAG, "Button create failed");
    }
    else
    {
        ESP_LOGE(TAG, "Button cb register!");
        iot_button_register_cb(gpio_btn, BUTTON_SINGLE_CLICK, button_single_click_cb, NULL);
        iot_button_register_cb(gpio_btn, BUTTON_LONG_PRESS_START, button_long_click_cb, NULL);
    }
}
